<?php
require_once('defs.php');

function do_list() {
    include('pages/people/list.php');
}

function do_add() {
    include('pages/people/add.php');
}

function do_add_do() {
    try {
	$name = $_GET['name'];
	if ($name == '') {
	    throw new Exception("Name can't be empty.");
	}

	$midname = $_GET['midname'];

	$lastname = $_GET['lastname'];
	if ($lastname == '') {
	    throw new Exception("Lastname can't be empty.");
	}

	$faculty = $_GET['faculty'];
	if ($faculty == '') {
	    throw new Exception("Faculty can't be empty.");
	}

	$gruppa = $_GET['gruppa'];
	if ($gruppa == '') {
	    throw new Exception("Gruppa can't be empty.");
	}

	$room = $_GET['room'];
	if ($room == '') {
	    throw new Exception("Room can't be empty.");
	}

	$roomcost = $_GET['roomcost'];
	if ($roomcost == '') {
	    throw new Exception("Room cost can't be empty.");
	}

	if (isset($_GET['id'])) {
	    $kid = $_GET['id'];
	    if ($kid == '') {
		throw new Exception("Invalid ppl id.");
	    }

	    $database = new PDO('sqlite:' . DBASEFILE);
	    if (!$database) {
		print("Database error.");
		return;
	    }
	    $query = "REPLACE INTO People (id, name, midname, lastname, faculty, gruppa, room, roomcost) VALUES ('$kid', '$name', '$midname', '$lastname', '$faculty', '$gruppa', '$room', '$roomcost');";
	    $database->exec($query);
	    unset($database);

	    echo json_encode(array('status_msg' => 'Сведения изменены.'));
	} else {
	    $database = new PDO('sqlite:' . DBASEFILE);
	    if (!$database) {
		print("Database error.");
		return;
	    }

	    $kid = time();

	    $query = "INSERT INTO People (id, name, midname, lastname, faculty, gruppa, room, roomcost) VALUES ('$kid', '$name', '$midname', '$lastname', '$faculty', '$gruppa', '$room', '$roomcost');";
	    $database->exec($query);
	    unset($database);

	    echo json_encode(array('status_msg' => 'Новый проживающий добавлен.'));
	}
    } catch (Exception $e) {
	echo json_encode(array('error_msg' => $e->getMessage()));
    }
}

function do_edit() {
    $kid = $_GET['id'];

    if (!$kid) {
	do_list();
    } else {
	$database = new PDO('sqlite:' . DBASEFILE);
	if (!$database) {
	    print("Database error.");
	    return;
	}
	$result = $database->query("SELECT * FROM People WHERE id LIKE '$kid';");
	$ppl= $result->fetch();
	unset($database);
	$editing = TRUE;
	include('pages/people/add.php');
    }
}

function do_delete()
{
    $kid = $_GET['id'];

    $database = new PDO('sqlite:' . DBASEFILE);
    if (!$database) {
        print("Database error.");
        return;
    }
    $database->exec("DELETE FROM People WHERE id LIKE '$kid';");
    unset($database);

    header('Location: student.php');
}

$cmd = $_GET['cmd'];

if ($cmd == 'add') {
    do_add();
} else if ($cmd == 'add_do') {
    do_add_do();
} else if ($cmd == 'edit') {
    do_edit();
} else if ($cmd == 'delete') {
    do_delete();
} else {
    do_list();
}

?>
